package com.lhcai.lc.category.hash;

import java.util.*;

/**
 * 49. 字母异位词分组
 *
 * @author liuhuaicai
 * @create 2024-07-08 21:13
 */
public class Lc49 {
    public static void main(String[] args) {
        Lc49 hot02 = new Lc49();
        String[] strs = new String[]{"aaa", "aaa"};
        List<List<String>> lists = hot02.groupAnagrams(strs);
        System.out.println(lists);
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            String cur = isAnagrams(str, map);
            if (map.containsKey(cur)) {
                List<String> curList = map.get(cur);
                curList.add(str);
                map.put(cur, curList);
            } else {
                ArrayList<String> curList = new ArrayList<>();
                curList.add(cur);
                map.put(str, curList);
            }
        }
        List<List<String>> res = new ArrayList<>();
        for (List<String> value : map.values()) {
            res.add(value);
        }
        return res;
    }

    private String isAnagrams(String str, Map<String, List<String>> map) {
        for (String s : map.keySet()) {
            if (solution(s, str)) {
                return s;
            }
        }
        return str;
    }

    private boolean solution(String s, String target) {
        if (s.length() != target.length()) {
            return false;
        }
        char[] sCharArray = s.toCharArray();
        char[] targetCharArray = target.toCharArray();
        Arrays.sort(sCharArray);
        Arrays.sort(targetCharArray);
        for (int i = 0; i < s.length(); i++) {
            if (sCharArray[i] != targetCharArray[i]) {
                return false;
            }
        }
        return true;
    }
}
